import type { D1Database } from '@cloudflare/workers-types';
import type { ApiResponse } from '../../../types';

interface Product {
  id: number;
  gd_name: string;
  actual_price: number;
  picture: string;
  gd_description: string;
}

interface Category {
  id: number | unknown;
  name: string | unknown;
  products: Product[] | unknown;
}

export default defineEventHandler(async (event): Promise<ApiResponse<Category[]>> => {
  try {
    const db = event.context.cloudflare.env.DB as D1Database;
    if (!db) {
      console.error('D1数据库绑定未在事件上下文中找到');
      return {
        success: false,
        message: '服务器配置错误，数据库不可用'
      };
    }

    // 获取所有启用的分类
    const groups = await db.prepare(
      'SELECT id, name, description FROM groups WHERE is_open = 1 AND deleted_at IS NULL ORDER BY ord DESC'
    ).all();

    if (!groups.results || groups.results.length === 0) {
      return {
        success: true,
        message: '没有找到商品分类',
        data: []
      };
    }

    // 为每个分类获取商品
    const categories: Category[] = [];
    
    for (const group of groups.results) {
      // 获取该分类下的所有启用商品
      const goods = await db.prepare(
        `SELECT id, gd_name, gd_description, picture, actual_price 
         FROM goods 
         WHERE group_id = ? AND is_open = 1 AND deleted_at IS NULL 
         ORDER BY ord DESC, id DESC 
         LIMIT 8`
      ).bind(group.id).all();

      if (goods.results && goods.results.length > 0) {
        // 转换商品数据格式
        const products = goods.results.map((item: any) => ({
          id: item.id,
          name: item.gd_name,
          price: `¥${item.actual_price.toFixed(2)}`,
          image: item.picture, // 默认图片
          description: item.gd_description
        }));

        categories.push({
          id: group.id,
          name: group.name,
          products: products
        });
      }
    }

    return {
      success: true,
      message: '获取商品分类成功',
      data: categories
    };
  } catch (error) {
    console.error('获取商品分类错误:', error);
    return {
      success: false,
      message: '获取商品分类失败，请稍后重试'
    };
  }
});